import React from 'react';
import { connect } from 'react-redux';
import { Form, Button, Input, Row, Col, Menu, Badge, Icon, Popover, Dropdown, Modal } from 'antd';
import config from 'config';
import menuRoute from 'routes/menuRoute';
import contractService from 'containers/approve/contract/contract.service';
import 'styles/contract/my-contract/my-contract.scss';
import moment from 'moment';
import SearchArea from 'components/search-area';
import debounce from 'lodash.debounce';
import contractStatus from 'containers/approve/contract/contract-status'
import CustomTable from 'containers/setting/contract-type-define/custom-table';
import { messages } from 'share/common';
import errorMessage from 'share/errorMessage';

const Search = Input.Search;
const statusList = [
  { value: 1001, label: messages('common.editing') },
  { value: 1002, label: messages('common.approving') },
  { value: 1003, label: messages('common.withdraw') },
  { value: 1004, label: messages('common.approve.pass') },
  { value: 1005, label: messages('common.approve.rejected') },
  { value: 6001, label: messages('my.contract.state.hold') },
  { value: 6002, label: messages('my.contract.state.cancel') },
  { value: 6003, label: messages('my.contract.state.finish') },
];

class MyContract extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      searchForm: [
        {
          type: 'input',
          id: 'contractName',
          label: messages('my.contract.name'/*合同名称*/)
        },
        {
          type: 'list',
          id: 'companyId',
          label: messages('my.contract.contractCompany'/*公司*/),
          listType: 'company',
          valueKey: 'id',
          labelKey: 'name',
          options: [],
          event: 'id',
          listExtraParams: { setOfBooksId: this.props.company.setOfBooksId },
          single: true
        },
        {
          type: 'list',
          id: 'contractTypeId',
          label: messages('my.contract.type'/*合同类型*/),
          single: true,
          labelKey: 'contractTypeName',
          valueKey: 'id',
          listType: 'contract_type',
          listExtraParams: { companyId: this.props.company.id },
        },
        {
          type: 'select',
          id: 'status',
          label: messages('common.column.status'/*状态*/),
          options: statusList
        },
        {
          type: 'items',   id: 'dateRange', items: [
            {
              type: 'date',
              id: 'signDateFrom',
              label: messages('my.contract.signDate.from'/*签署日期从*/)
            },
            { type: 'date', id: 'signDateTo', label: messages('my.contract.signDate.to'/*签署日期至*/) }]
        },
        {
          type: 'value_list',
          id: 'partnerCategory',
          label: messages('my.contract.partner.category'/*合同方类型*/),
          valueListCode: 2107,
          options: [],
          event: 'CON_PARTNER_TYPE',
        },
        {
          type: 'list',
          listType: 'bgtUser',
          id: 'partnerId',
          label: messages('my.contract.partner'/*合同方*/),
          single: true,
          valueKey: 'id',
          disabled: true,
          labelKey: 'name',
        },
        {
          type: 'select',
          id: 'currency',
          label: messages('common.currency'/*币种*/),
          options: [],
          getUrl: `/api/currency/status/query/by/setOfBooksId?userOId=${props.user.userOID}`,
          method: 'get',
          labelKey: 'currency',
          valueKey: 'currency',
        },
        {
          type: 'items',   id: 'amountRange', items: [
            {
              type: 'input',
              id: 'amountFrom',
              label: messages('my.contract.amount.from'/*合同金额从*/)
            },
            { type: 'input', id: 'amountTo', label: messages('my.contract.amount.to'/*合同金额至*/) }
          ]
        },
        {
          type: 'input',   id: 'remark', label: messages('common.comment'/*备注*/)
        }
      ],
      searchParams: {},
      columns: [
        {
          title: messages('my.contract.number'/*合同编号*/),
          dataIndex: 'contractNumber',
          width: 150,
          render: desc => <Popover placement="topLeft" content={desc}>{desc ? desc : ''}</Popover>
        },
        {
          title: messages('my.contract.name'/*合同名称*/),
          width: 200,
          dataIndex: 'contractName',
          render: desc => <Popover placement="topLeft" content={desc}>{desc ? desc : ''}</Popover>
        },
        {
          title: messages('my.contract.contractCompany'/*合同公司*/),
          dataIndex: 'companyName',
          render: desc => <Popover placement="topLeft" content={desc}>{desc ? desc : ''}</Popover>
        },
        {
          title: messages('my.contract.signDate'/*签署日期*/),
          dataIndex: 'signDate',
          width: 100,
          render: desc => <Popover placement="topLeft" content={moment(desc)
            .format('YYYY-MM-DD')}>{desc ? moment(desc)
            .format('YYYY-MM-DD') : '-'}</Popover>,
        },
        {
          title: messages('my.contract.part'),
          dataIndex: 'partnerCategoryName',
          render: (value, record) => {
            return (
              value ?
                <div>
                  {value}
                  <span className="ant-divider"/>
                  {record.partnerName}
                </div> : '-'
            );
          }
        },
        {
          title: messages('my.contract.currency'/*币种*/),
          dataIndex: 'currency',
          width: '5%',
          render: desc => <Popover placement="topLeft" content={desc}>{desc ? desc : ''}</Popover>
        },
        {
          title: messages('my.contract.amount'/*合同金额*/),
          dataIndex: 'amount',
          width: 110,
          render: desc => <Popover placement="topLeft" content={this.filterMoney(desc, 2)}>{this.filterMoney(desc, 2)}</Popover>
        },
        {
          title: messages('common.column.status'/*状态*/),
          dataIndex: 'status',
          width: '110px',
          render: value => <Badge status={contractStatus[value].state} text={contractStatus[value].label}/>
        }
      ],
      data: [],
      contractType: [],
      page: 0,
      pageSize: 10,
      pagination: {
        total: 0,
        showQuickJumper: true,
        showSizeChanger: true
      },
      company: '',
      NewContract: menuRoute.getRouteItem('new-contract', 'key'), //新建合同
      ContractDetail: menuRoute.getRouteItem('contract-detail', 'key'), //合同详情
    };
    this.searchNumber = debounce(this.searchNumber, 500);
  }

  componentDidMount() {
    this.getContractType();
  }

  getContractType = () => {
    let params = {
      companyId: this.props.company.id
    };
    contractService.getContractTypeByCompany(params)
      .then(response => {
        if (!response.data[0]) {
          Modal.warning({
            title: '提示',
            content: messages('contract.key54')/*当前公司下无可用的合同类型，请联系管理员！*/,
          });
        }
        this.setState({ contractType: response.data });
      })
      .catch((e) => {
        errorMessage(e.response);
      });
  };


  searchNumber = (e) => {
    this.setState({
      searchParams: { ...this.state.searchParams, contractNumber: e }
    }, () => {
      this.customTable.search({ ...this.state.searchParams, contractNumber: e });
    });
  };


  //搜索
  search = (values) => {
    values.signDateFrom && (values.signDateFrom = moment(values.signDateFrom)
      .format('YYYY-MM-DD'));
    values.signDateTo && (values.signDateTo = moment(values.signDateTo)
      .format('YYYY-MM-DD'));
    this.setState({ ...this.state.searchParams, ...values }, () => {
      this.customTable.search({ ...this.state.searchParams, ...values });
    });
  };

  clear = () => {
    const { searchForm } = this.state;
    searchForm[6].disabled = true;
    this.setState({
      searchForm
    });
    this.eventHandle('id', null);
    this.eventHandle('code', null);
  };

  //新建
  handleNew = () => {
    this.context.router.push(this.state.NewContract.url);
  };

  //合同详情
  rowClick = (record) => {
    this.context.router.push(this.state.ContractDetail.url.replace(':id', record.id).replace(':from', 'contract'));
  };

  eventHandle = (type, value) => {
    let searchForm = this.state.searchForm;
    const {companyOID } = this.props.company;
    switch (type) {
      case 'CON_PARTNER_TYPE': {
        if (value) {
          searchForm[6].disabled = false;
          let listObj = {
            'EMPLOYEE': () => {
              searchForm[6].listType = 'bgtUser';
              searchForm[6].listExtraParams = {};
              searchForm[6].labelKey = 'fullName';
            },
            'VENDER': () => {
              searchForm[6].listType = 'vendor_account';
              searchForm[6].listExtraParams = { companyOid: companyOID };
              searchForm[6].labelKey = 'venNickname';
            }
          };
          listObj[value]();
          this.formRef.setValues({ partnerId: [] });
        } else {
          this.formRef.setValues({ partnerId: [] });
          searchForm[6].disabled = true;
        }
        break;
      }
    }
    this.setState({ searchForm });
  };

  //新建
  handleCreate = (e) => {
    this.context.router.push(this.state.NewContract.url.replace(':contractTypeId', e.key));
  };


  render() {
    const { searchForm, columns, contractType } = this.state;
    return (
      <div className="my-contract">
        <SearchArea searchForm={searchForm}
                    eventHandle={this.eventHandle}
                    submitHandle={this.search}
                    clearHandle={this.clear}
                    wrappedComponentRef={(inst) => this.formRef = inst}/>
        <div className='divider'/>
        <Row gutter={24} style={{ marginBottom: 12 }}>
          <Col span={18}>
            <Dropdown overlay={<Menu onClick={this.handleCreate}>{contractType.map(item => <Menu.Item
                key={item.id}>{item.contractTypeName}</Menu.Item>)}</Menu>}>
              <Button type="primary">
                {messages('menu.new-contract')}<Icon type="down"/>
              </Button>
            </Dropdown>
          </Col>
          <Col span={6}>
            <Search
              placeholder={messages('my.please.input.number')}
              onSearch={this.searchNumber}
              className="search-number"
              enterButton
            />
          </Col>
        </Row>
        <CustomTable
          ref={ref => this.customTable = ref}
          columns={columns}
          onClick={this.rowClick}
          url={`${config.contractUrl}/api/contract/header/update/query`}
        />
      </div>
    );
  }
}

MyContract.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user
  };
}

const wrappedMyContract = Form.create()((MyContract));

export default connect(mapStateToProps, null, null, { withRef: true })(wrappedMyContract);
